<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\Api\TemplateMessageException;
use App\Services\WxTemplatemsgService;
use function GuzzleHttp\Promise\all;
use Illuminate\Http\Request;
use App\Models\WxTemplatemsg;

/**
 * Class TemplateMessageController
 * @package App\Http\Controllers\Api
 * 模板消息接口
 */
class TemplateMessageController extends BaseController
{

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws TemplateMessageException
     */
    public function send(Request $request)
    {

            $validator = \Validator::make($request->all(), [
                'touser' => 'required', //微信用户openid微信用户openid
                'template_key' => 'required', //模板key
                'data' => 'required', //消息数据 json
                //'url' => 'required', //模板消息的点击跳转地址(http://...)
            ]);

            if ($validator->fails()) {
                throw new TemplateMessageException($validator->errors()->first(), TemplateMessageException::DATA_VALIDATOR_FAILURE);
            }

            $template_key = $request->input('template_key');

            $find = WxTemplatemsg::where('template_key', $template_key)->first();
            if (empty($find)){
                throw new TemplateMessageException('无效的模板标识', TemplateMessageException::TEMPLATE_KEY_INVALID);
            }

            $data = [
                    'touser' => $request->input('touser'),
                    'url' => $request->input('url', ''),
                    'data' => json_decode($request->input('data'), true)
            ];

            if (!empty($request->input('miniprogram')) && json_decode($request->input('miniprogram'), true)){
                $data['miniprogram'] = json_decode($request->input('miniprogram'), true);
            }

            //队列异步发送
            \App\Jobs\WxTemplateSend::dispatch($template_key, $data)->onQueue('default');

            //server即时发送
            /*$res = (new WxTemplatemsgService())->send($template_key, $data);
            if ($res->errcode !== 0){
                throw new TemplateMessageException($res->errmsg, $res->errcode);
            }*/

            return $this->responseJson(0, 'success');

    }

}